//
//  ZYRWLock.m
//  OC_Principle
//
//  Created by wangzhipan on 2025/2/18.
//

#import "ZYRWLock.h"
#import <pthread/pthread.h>

@interface ZYRWLock() {
    pthread_rwlock_t _rwLock;
    
    int _age;
}

@end

@implementation ZYRWLock
- (instancetype)init
{
    if (self = [super init]) {
        /*
         pthread_rwlock：读写锁，实现多读单写
         */
        pthread_rwlock_init(&_rwLock, NULL);
        _age = 0;
    }
    return self;
}

- (void)dealloc
{
    pthread_rwlock_destroy(&_rwLock);
}

- (void)setup
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self write:10];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self write:15];
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self read];
    });
}

- (int)read
{
    int x;
    //给read加锁
    pthread_rwlock_rdlock(&_rwLock);
    sleep(1);
    x = _age;
    NSLog(@"%s:: %d", __func__, x);
    pthread_rwlock_unlock(&_rwLock);
    return x;
}

- (void)write:(int)x
{
    pthread_rwlock_wrlock(&_rwLock);
    sleep(2);
    _age = x;
    NSLog(@"%s:: %d", __func__, x);
    pthread_rwlock_unlock(&_rwLock);
}
@end
